﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CPPEI.Coolzon.ServiceProxy.DataServiceRef;
using System.Windows.Media.Animation;
using Visifire.Charts;
using CPPEI.Coolzon.Common;

namespace CPPEI.Coolzon.UI.DataPartLib
{
    /// <summary>
    /// Interaction logic for DataChartSectors.xaml
    /// </summary>
    [System.ComponentModel.DisplayName("扇形图")]
    [XPartIcon("pack://application:,,,/CPPEI.Coolzon.UI.DataPartLib;component/Images/PartIcons/扇形图.png")]
    [XPart("ChartSectors", "扇形图")]
    public partial class DataChartSectors : DataPart
    {
        private Storyboard _animationStoryboard;

        public DataChartSectors()
        {
            XFontSize = 12;
            SetDefaultDataResult();
            InitializeComponent();
        }
        private void SetDefaultDataResult()
        {
            Random random = new Random();
            ServiceProxy.DataServiceRef.DataSeries[] series = new ServiceProxy.DataServiceRef.DataSeries[1];
            ServiceProxy.DataServiceRef.DataItem[] tmpItems = new ServiceProxy.DataServiceRef.DataItem[10];
            for (int i = 1; i <= tmpItems.Length; i++)
            {
                tmpItems[i - 1] = new ServiceProxy.DataServiceRef.DataItem();
                tmpItems[i - 1].Id = "data" + i;
                tmpItems[i - 1].Name = "data" + i;
                tmpItems[i - 1].Value = random.NextDouble().ToString("F2");
            }
            series[0] = new ServiceProxy.DataServiceRef.DataSeries();
            series[0].DataItems = tmpItems;
            DataResult = new ServiceProxy.DataServiceRef.DataResult();
            DataResult.DataSeries = series;
        }

        protected override void OnInit(PartContext context)
        {
            base.OnInit(context);
        }

        protected override void OnActive(PartContext context)
        {
            base.OnActive(context);
        }

        protected override void OnDeactive(PartContext context)
        {
            if (_animationStoryboard != null)
            {
                _animationStoryboard.Stop();
                _animationStoryboard.Remove();
                _animationStoryboard = null;
            }

            base.OnDeactive(context);
        }

        protected override void OnDestory()
        {
            if (_animationStoryboard != null)
            {
                _animationStoryboard.Stop();
                _animationStoryboard.Remove();
                _animationStoryboard = null;
            }
            base.OnDestory();
        }

        protected override void OnDataBinding(DataResult dataResult)
        {
            ClearAnimation();
            StopAnimation();
            _animationStoryboard = new Storyboard();
            _animationStoryboard.FillBehavior = FillBehavior.HoldEnd;
            _animationStoryboard.Completed += _animationStoryboard_Completed;
            
            if (dataResult.DataSeries.Length > 0)
            {
                grid.Children.Clear();
                grid.Children.Add(arcCircle);

                // 只取第一串数据
                ServiceProxy.DataServiceRef.DataSeries dataSeries = DataResult.DataSeries[0];

                double animationInteval = (XDataAnimationDuration) / (double)dataSeries.DataItems.Length;
                int totalItemCount = dataSeries.DataItems.Length;
                int offsetAngle = 360 / totalItemCount;
                for (int itemIndex = 0; itemIndex < totalItemCount; itemIndex++)
                {
                    ServiceProxy.DataServiceRef.DataItem dataItem = dataSeries.DataItems[itemIndex];
                    DataChartSector dataChartSector = null;
                    int startAngle = 270 + offsetAngle * itemIndex;
                    int endAngle = 270 + ((itemIndex + 1) == totalItemCount ? 360 : offsetAngle * (itemIndex + 1));

                    dataChartSector = new DataChartSector(Width, Height, startAngle, endAngle, dataItem.Value, dataItem.Name, totalItemCount, itemIndex + 1);

                    if (XColorPlate != null)
                        dataChartSector.FillBrush = XColorPlate.GetColor(itemIndex);
                    if (XFontFamily != null)
                        dataChartSector.FontFamily = XFontFamily;
                    if (XForeground != null)
                        dataChartSector.Foreground = XForeground.Brush;

                        dataChartSector.FontWeight = XFontWeight;
                    if (XIsLineVisible != null)
                        dataChartSector.IsLineVisible = XIsLineVisible.Value;
                    else
                        dataChartSector.IsLineVisible = false;

                    if (XItemNameVisible != null)
                        dataChartSector.IsItemNameVisible = XItemNameVisible.Value;
                    else
                        dataChartSector.IsItemNameVisible = false;

                    if (XItemValueVisible != null)
                        dataChartSector.IsItemValueVisible = XItemValueVisible.Value;
                    else
                        dataChartSector.IsItemValueVisible = false;

                    dataChartSector.FontSize = XFontSize;

                    Panel.SetZIndex(dataChartSector, 0);
                    grid.Children.Add(dataChartSector);

                    DoubleAnimation animation = new DoubleAnimation(startAngle, endAngle, new Duration(TimeSpan.FromSeconds(animationInteval)));
                    animation.BeginTime = TimeSpan.FromSeconds((itemIndex + 1) * animationInteval);
                    Storyboard.SetTarget(animation, dataChartSector);
                    Storyboard.SetTargetProperty(animation, new PropertyPath(DataChartSector.ArcEndAngleProperty));
                    _animationStoryboard.Children.Add(animation);
                }

                if (_animationStoryboard != null)
                {
                    _animationStoryboard.Begin();
                }
            }
        }
        protected override void OnApplyXProperty()
        {
            base.OnApplyXProperty();
        }

        /// <summary>
        /// 动画完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _animationStoryboard_Completed(object sender, EventArgs e)
        {
            ClearAnimation();
        }

        /// <summary>
        /// 清理动画，清理故事版中每个动画的target，防止内存溢出
        /// </summary>
        private void ClearAnimation()
        {
            if (_animationStoryboard != null)
            {
                foreach (Timeline tl in _animationStoryboard.Children)
                {
                    tl.ClearValue(Storyboard.TargetProperty);
                }
            }
        }
        private void StopAnimation()
        {
            if (_animationStoryboard != null)
            {
                _animationStoryboard.Completed -= _animationStoryboard_Completed;
                _animationStoryboard.Stop();
                _animationStoryboard.Remove();
                _animationStoryboard = null;
            }
        }
    }
}
